/**
 * @author        Nicolas Bottarini <nicolasbottarini@gmail.com>, 404 <http://www.proyecto404.com>
 * @version       $Rev: 3 $
 * @lastrevision  $Date: 2011-09-12 16:45:37 +0000 (Mon, 12 Sep 2011) $	 
 */
package com.proyecto404.core.mvc {
	import com.proyecto404.core.BaseObject;
	import com.proyecto404.core.log.fireflash.Console;
	import com.proyecto404.core.util.ClassHelper;

	public class Bootstrapper extends BaseObject {
		private var _tasks:Vector.<IBootstrapperTask>;
		private var _finishCallback:Function;
		
		public function Bootstrapper(finishCallback:Function = null) {
			_tasks = new Vector.<IBootstrapperTask>();
			_finishCallback = finishCallback;
		}
		
		public function registerTask(task:IBootstrapperTask):void {
			_tasks.push(task);
		}
		
		public function run():void {
			runNextTask();
		}
		
		private function runNextTask():void {
			if (_tasks.length == 0) {
				if (_finishCallback != null) {
					_finishCallback.call(this);
				}
				return; 
			}
			var task:IBootstrapperTask = _tasks.shift();
			Console.debug('[Bootstrapper] Executing ' + ClassHelper.getClassName(task) + '...');
			task.taskCompleted.addOnce(onTaskCompleted);
			task.execute();
		}
		
		private function onTaskCompleted():void {
			runNextTask();
		}
	}
}